package com.lxy.dao.redis;

import com.lxy.pojo.SecKill;
import com.lxy.utils.ProtoStuffRedisSerializer;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * Redis的Dao层访问
 *
 * @author Manaka
 * @date 2020-03-07 18:15
 */
@Repository
public class RedisDao {

    @Resource
    private RedisTemplate<Long, SecKill> redisTemplate;

    /**
     * ProtoStuff序列化与反序列化工具
     */
    private final static ProtoStuffRedisSerializer protoStuffRedisSerializer = new ProtoStuffRedisSerializer();

    public SecKill getSecKill(long secKillId) {
        String key = "seckillId:" + secKillId;
        byte[] result = redisTemplate.execute((RedisCallback<byte[]>) connection -> connection.get(key.getBytes()));
        if (result == null) {
            return null;
        }

        return (SecKill) protoStuffRedisSerializer.deserialize(result);
    }


    public void putSecKill(SecKill secKill) {
        String key = "seckillId:" + secKill.getSeckillId();
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            //超时缓存
            int timeout = 60 * 60;
            connection.setEx(key.getBytes(), timeout, protoStuffRedisSerializer.serialize(secKill));
            return null;
        });
    }
}
